import { Inject, Injectable } from '@nestjs/common';
import { Email } from 'src/utils/EmailTool';
import { UserService } from 'src/user/user.service';
import { BUSINESS_ERROR_CODE } from 'src/common/exceptions/business.error.codes';
import { BusinessException } from 'src/common/exceptions/business.exception';
import * as CryptoJS from 'crypto-js';
import { AuthService } from '../auth/auth.service';
import { Repository } from 'typeorm';
import { UserEntity } from 'src/user/entities/user.entity';
import { CreateUserDto } from 'src/user/dto/create-user.dto';
import { LoginDto } from './dto/login.dto';

@Injectable()
export class ApiUserService {
  constructor(
    private readonly userService: UserService,
    private readonly authService: AuthService,
    @Inject('USER_REPOSITORY') //注入用户数据库依赖
    private readonly userRepository: Repository<UserEntity>,
  ) {}
  // 发生邮箱验证码
  getCode(email: string) {
    try {
      new Email().send({
        email: email,
        subject: 'WEBXUE - 欢迎注册',
      });
    } catch (error) {
      console.log(error);
    }
  }
  // 验证邮箱验证码
  async sign(payload: LoginDto) {
    const user = await this.userService.validate(
      payload.username,
      payload.password,
    );
    if (user) {
      throw new BusinessException({
        code: BUSINESS_ERROR_CODE.COMMON,
        message: '该邮箱已被注册',
      });
    }

    return this.userService.create({
      ...payload,
      avatar_url: '',
      password: CryptoJS.MD5(payload.password).toString(),
    });
  }
  // 登录处理
  async login(payload: CreateUserDto) {
    const user = await this.userRepository.findOne({
      where: {
        username: payload.username,
        password: CryptoJS.MD5(payload.password).toString(),
      },
    });

    if (user) {
      const data = this.authService.createToken({
        id: user.id,
        username: user.username,
      });
      delete user.password; //删除密码
      return {
        ...user,
        token: data.access_token,
      };
    } else {
      return this.register(payload);
    }
  }

  // 注册处理
  async register(payload: LoginDto) {
    const user = await this.userRepository.findOne({
      where: {
        username: payload.username,
      },
    });
    if (user) {
      throw new BusinessException({
        code: BUSINESS_ERROR_CODE.COMMON,
        message: '该用户以注册',
      });
    } else {
      const user = await this.userService.create({
        ...payload,
        avatar_url: '',
        password: CryptoJS.MD5(payload.password).toString(),
      });
      const data = this.authService.createToken({
        id: user.id,
        username: user.username,
      });
      delete user.password; //删除密码
      return {
        ...user,
        token: data.access_token,
      };
    }
  }

  // 获取用户信息
  getUser(user: UserEntity) {
    return this.userRepository.findOne({
      select: ['username', 'avatar_url'],
      where: {
        id: user.id,
      },
    });
  }
  updateUserInfo(user: UserEntity, payload) {
    return this.userRepository.update(user.id, payload);
  }
}
